# 导入模块
import numpy as np
import matplotlib.pyplot as plt

# 创造实验数据
x0 = np.arange(1, 16).reshape(-1, 1)  # 这里我们选取15个点，将数组转换为列向量
# 使用 y = (x-5)^2 = x^2+10*x+25, 作为模型函数并添加噪声
y0 = ((x0 - 5) ** 2 + np.random.uniform(0, 10, size=(len(x0), 1))).reshape(-1, 1)

# 构造特性矩阵
'''
该特性矩阵一共有三列，第一列为全为1，第二列为向量x，第三列为向量x^2
'''
first = np.ones((len(x0))).reshape(-1, 1)
second = x0
third = x0 ** 2
X = np.concatenate((first, second, third), axis=1)

X_T = X.transpose()
beta = np.linalg.inv(X_T.dot(X)).dot(X_T).dot(y0)

print("系数矩阵:\n{0}".format(beta))

yi = beta[0] + beta[1] * x0 + beta[2] * (x0 ** 2)

fig = plt.figure()
sub = plt.subplot(111)
sub.scatter(x0, y0)
sub.plot(x0, yi)

plt.show()
